package com.cheboohui.iqs.spider.pingan;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.message.BasicNameValuePair;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cheboohui.iqs.common.basic.StringUtil;
import com.cheboohui.iqs.config.Config;
import com.cheboohui.iqs.http.tool.HttpClient;
import com.cheboohui.iqs.menu.ErrorNews;
import com.cheboohui.iqs.spider.login.LoginEntity;
import com.cheboohui.iqs.spider.pingan.entity.PAResult;
import com.cheboohui.iqs.spring.entity.Car;
import com.cheboohui.iqs.spring.entity.CarNews;
import com.cheboohui.iqs.spring.entity.DrivingLicense;
import com.cheboohui.iqs.spring.entity.price.response.CheckCarResult;

/**
 * 平安车辆查询
 * 
 * @author xielonghai
 *
 */
public class CheckCarPingAn {
	/**
	 * logger:日志工具.
	 */
	private static Log log = LogFactory.getLog(CheckCarPingAn.class);

	/**
	 * 平安爬虫车辆查询
	 * 
	 * @param login
	 * @param license
	 * @return
	 */
	public static CheckCarResult getCar(LoginEntity login, DrivingLicense license) {
		if (!login.isState())
			return new CheckCarResult(ErrorNews.L02, "登录平安系统失败,未获取得到验证码");
		log.info(Config.value + "," + login.getOrderNo() + ",车型获取:车架:" + license.getFrameNo() + ",厂牌:"
				+ license.getLabelNo());
		
		if('L'==license.getFrameNo().charAt(0))
			return getCarByLabel(license.getLabelNo(), login);
		else
			return getCarByFrame(license.getFrameNo(), login);
	}

	/**
	 * 根据车架号查车
	 * 
	 * @param frameNo
	 * @param login
	 * @return
	 */
	public static CheckCarResult getCarByFrame(String frameNo, LoginEntity login) {
		if (!login.isState())
			return new CheckCarResult(ErrorNews.L02, "登录平安系统失败,未获取得到验证码");

		log.info(login.getOrderNo() + ",根据车架号获取得到车辆数据,车架号:" + frameNo);
		ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("vehicleFrameNo", frameNo));
		params.add(new BasicNameValuePair("departmentCode", "21825"));
		params.add(new BasicNameValuePair("insuranceType", "1"));
		try {

			log.info(login.getOrderNo() + ",根据车架号获取得到车辆数据,车架号:" + frameNo + ",请求开始...");

			String res = HttpClient._httpPostToBody(login.getHttpClient(), login.getHttpContext(),
					"https://icorepnbs.pingan.com.cn/icore_pnbs/do/app/quotation/autoModelCodeQuery", params);

			log.info(login.getOrderNo() + ",根据车架号获取得到车辆数据,车架号:" + frameNo + ",处理-->厂牌型号...");
			String label = getBrandPara(res);
			if (StringUtil.isNulls(label)) {
				log.error(login.getOrderNo() + ",根据车架号获取得到的车辆数据:" + res);
				return new CheckCarResult(ErrorNews.L03, "平安爬虫系统,根据车架号查询获取厂牌型号错误");
			}

			log.info(login.getOrderNo() + ",根据车架号获取得到车辆数据,车架号:" + frameNo + ",处理-->厂牌型号-->进行厂牌型号查车...");
			return getCarByLabel(label, login);
		} catch (Exception e) {
			log.error(login.getOrderNo() + ",根据车架号获取得到车辆数据,出现异常:" + e);
			return new CheckCarResult(ErrorNews.L03, "平安爬虫系统,根据车架号查询车辆出现异常:" + e.getMessage());
		}

	}

	/**
	 * 根据厂牌型号查车
	 * 
	 * @param labelNo
	 * @param login
	 * @return
	 */
	public static CheckCarResult getCarByLabel(String labelNo, LoginEntity login) {
		if (!login.isState())
			return new CheckCarResult(ErrorNews.L02, "登录平安系统失败,未获取得到验证码");

		log.info(login.getOrderNo() + ",根据厂牌型号获取得到车辆数据,厂牌型号:" + labelNo);
		ArrayList<BasicNameValuePair> param = new ArrayList<BasicNameValuePair>();
		param.add(new BasicNameValuePair("brandPara", labelNo));
		param.add(new BasicNameValuePair("departmentCode", "21825"));
		param.add(new BasicNameValuePair("insuranceType", "1"));
		param.add(new BasicNameValuePair("rateClassFlag", "14"));
		try {
			log.info(login.getOrderNo() + ",根据厂牌型号获取得到车辆数据,厂牌型号:" + labelNo + ",请求开始...");

			String res = HttpClient._httpPostToBody(login.getHttpClient(), login.getHttpContext(),
					"https://icorepnbs.pingan.com.cn/icore_pnbs/do/app/quotation/queryAutoModelType", param);

			log.info(login.getOrderNo() + ",根据厂牌型号获取得到车辆数据,厂牌型号:" + labelNo + ",处理返回车型列表...:"+res);
			JSONArray check = JSONObject.parseObject(res).getJSONObject("data").getJSONArray("encodeDict");

			if (null == check || check.isEmpty() || check.size() < 1) {
				log.error(login.getOrderNo() + ",根据厂牌型号获取得到车辆数据:" + res);
				return new CheckCarResult(ErrorNews.C02, "查询得到的车型列表为空");
			}

			return new CheckCarResult(toResult(check));
		} catch (Exception e) {
			log.error(login.getOrderNo() + ",根据厂牌型号获取得到车辆数据,出现异常:" + e);
			return new CheckCarResult(ErrorNews.L03, "平安爬虫系统,根据厂牌型号查询车辆出现异常:" + e.getMessage());
		}
	}

	/**
	 * 车型列表处理
	 * 
	 * @param check
	 * @return
	 */
	public static List<CarNews> toResult(JSONArray check) {
		List<CarNews> listCar = new ArrayList<>();
		for (int k = 0; k < check.size(); k++) {
			JSONObject obj = check.getJSONObject(k);
			CarNews car = new CarNews();
			if (StringUtil.isNulls(obj.getString("autoModelCode")))
				car.setAutoModelCode(obj.getString("circAutoModelCode"));
			else
				car.setAutoModelCode(obj.getString("autoModelCode"));
			car.setAutoModelName(obj.getString("autoModelName"));
			car.setExhaustMeasure(obj.getString("exhaustMeasure"));
			car.setFirstSaleDate(obj.getString("firstSaleDate"));
			car.setPurchasePrice(obj.getString("purchasePrice"));
			if (StringUtil.isNulls(obj.getString("remark")))
				car.setRemark(obj.getString("optionDisplay"));
			else
				car.setRemark(obj.getString("remark"));
			car.setSeats(obj.getString("seats"));
			car.setOptionDisplay();
			listCar.add(car);
			// listCar.add(JSONObject.toJavaObject(check.getJSONObject(k),
			// PingAnCarEntity.class));
		}
		return listCar;
	}

	/**
	 * 车险报价时查车
	 * 
	 * @param car
	 * @param login
	 * @return
	 */
	public static PAResult getCarByLabel(Car car, LoginEntity login) {
		if (!login.isState())
			return new PAResult(ErrorNews.L02, "登录平安系统失败,未获取得到验证码");

		log.info(login.getOrderNo() + ",根据<车险报价查车>厂牌型号获取得到车辆数据,厂牌型号:" + car.getAutoModelCode());
		ArrayList<BasicNameValuePair> param = new ArrayList<BasicNameValuePair>();
		param.add(new BasicNameValuePair("brandPara", car.getAutoModelCode()));
		param.add(new BasicNameValuePair("departmentCode", "21825"));
		param.add(new BasicNameValuePair("insuranceType", "1"));
		param.add(new BasicNameValuePair("rateClassFlag", "14"));
		try {
			log.info(login.getOrderNo() + ",根据<车险报价查车>厂牌型号获取得到车辆数据,厂牌型号:" + car.getAutoModelCode() + ",请求开始...");

			String res = HttpClient._httpPostToBody(login.getHttpClient(), login.getHttpContext(),
					"https://icorepnbs.pingan.com.cn/icore_pnbs/do/app/quotation/queryAutoModelType", param);

			log.info(login.getOrderNo() + ",根据<车险报价查车>厂牌型号获取得到车辆数据,厂牌型号:" + car.getAutoModelCode() + ",处理返回车型列表...");
			JSONArray check = JSONObject.parseObject(res).getJSONObject("data").getJSONArray("encodeDict");

			if (null == check || check.isEmpty() || check.size() < 1) {
				log.error(login.getOrderNo() + ",根据<车险报价查车>厂牌型号获取得到车辆数据:" + res);
				return new PAResult(ErrorNews.C02, "<车险报价查车>查询得到的车型列表为空");
			}

			for (int k = 0; k < check.size(); k++) {
				JSONObject obj = check.getJSONObject(k);
				if (car.getPurchase() == obj.getDoubleValue("purchasePrice")) {
					PAResult result = new PAResult(obj);
					result.setCarList(check);
					return result;
				}
			}
			PAResult result = new PAResult(ErrorNews.C05, "平安车型库没有你所选择的车辆");
			result.setCarList(check);
			return result;
		} catch (Exception e) {
			log.error(login.getOrderNo() + ",根据<车险报价查车>厂牌型号获取得到车辆数据,出现异常:" + e);
			return new PAResult(ErrorNews.L03, "平安爬虫系统,根据<车险报价查车>厂牌型号查询车辆出现异常:" + e.getMessage());
		}
	}

	/**
	 * <取厂牌型号>
	 * 
	 * @param json
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	private static String getBrandPara(String json) {
		try {
			if (StringUtil.isNulls(json))
				return null;
			return JSONObject.parseObject(json).getJSONArray("encodeDict").getJSONObject(0).getString("autoModelName");
		} catch (Exception e) {
			log.error("厂牌型号提取异常错误:" + e);
			return null;
		}
	}
}
